from django.http import *
from google.appengine.api import users
from db import *
from ytbase.model.auth import *

def _default_view(request):
    return HttpResponseNotFound()

#authorization decorator
def authorize(cls, operation, view=_default_view, func=get_auth):
    def decorator(method):
        def new_method(request, *args, **kwds):
            obj = None
            if kwds.has_key('id') and operation != OPERATION_ADD:
                obj = get_by_str_id(cls, kwds['id'])
                    
            auth = func((cls, obj))

            if auth.has_key(operation):
                auth_result = auth[operation]
            else:
                auth_result = False
                
            if auth_result == False:
                return view(request)
            
            return method(request, *args, **kwds)            
        return new_method
    return decorator

#user authorization decorator
def authorize_user(view=_default_view, func=users.get_current_user):
    def decorator(method):
        def new_method(request, *args, **kwds):
            if not func():
                return view(request)
            return method(request, *args, **kwds)            
        return new_method
    return decorator

#admin authorization decorator
def authorize_admin(view=_default_view, func=users.is_current_user_admin):
    def decorator(method):
        def new_method(request, *args, **kwds):
            if not func():
                return view(request)
            return method(request, *args, **kwds)            
        return new_method
    return decorator
